package com.smomo.blog.service.front.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smomo.blog.common.Constants;
import com.smomo.blog.common.RedisConstants;
import com.smomo.blog.common.ResponseResult;
import com.smomo.blog.entity.Tags;
import com.smomo.blog.entity.WebConfig;
import com.smomo.blog.mapper.*;

import com.smomo.blog.service.front.ApiHomeService;
import com.smomo.blog.service.front.RedisService;
import com.smomo.blog.utils.IpUtil;
import com.smomo.blog.utils.MyHttpUtil;
import com.smomo.blog.vo.ApiArticleListVO;
import com.smomo.blog.vo.HomeDataVo;
import com.smomo.blog.vo.SystemArticleListVO;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Optional;

import static com.smomo.blog.common.FieldConstants.LIMIT_ONE;

@Service
@RequiredArgsConstructor
public class ApiHomeServiceImpl implements ApiHomeService {

    private final RedisService redisService;

    private final WebConfigMapper webConfigMapper;

    private final ArticleMapper articleMapper;

    private final TagsMapper tagsMapper;




    /**
     * 添加访问量
     * @return
     */

    public ResponseResult report() {
        // 获取ip
        String ipAddress = IpUtil.getIp();
        // 通过浏览器解析工具类UserAgent获取访问设备信息
        UserAgent userAgent = IpUtil.getUserAgent(IpUtil.getRequest());
        //获取游览器信息
        Browser browser = userAgent.getBrowser();
        //获取操作系统
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        // 生成唯一用户标识
        String uuid = ipAddress + browser.getName() + operatingSystem.getName();
        //md5加密
        String md5 = DigestUtils.md5DigestAsHex(uuid.getBytes());
        // 判断是否访问,生成唯一身份标识，每次访问先判断是否之前访问过的。
        if (!redisService.sIsMember(RedisConstants.UNIQUE_VISITOR, md5)) {
            // 访客量+1
            redisService.incr(RedisConstants.UNIQUE_VISITOR_COUNT, 1);
            // 保存唯一标识
            redisService.sAdd(RedisConstants.UNIQUE_VISITOR, md5);
        }
        //访问量永远加1
        // 访问量+1
        redisService.incr(RedisConstants.BLOG_VIEWS_COUNT, 1);

        return ResponseResult.success();
    }

    /**
     * 获取首页数据
     * @return
     */
    public ResponseResult getHomeData() {


        Object cacheObject = redisService.getCacheObject(Constants.HOME_DATA);
         if(cacheObject==null)
         {
             //获取首页轮播文章
             List<SystemArticleListVO> articles = articleMapper.selectListByBanner();

             //获取标签云
             List<Tags> tags = tagsMapper.selectList(null);

             //推荐文章
             List<ApiArticleListVO> apiArticleListVOS = articleMapper.selectRecommendArticle();
             redisService.setCacheObject(Constants.HOME_DATA,new HomeDataVo(articles,tags,apiArticleListVOS));
             return ResponseResult.success().putExtra("articles",articles).putExtra("newArticleList",apiArticleListVOS).putExtra("tagCloud",tags);
         }
         HomeDataVo homeDataVo= (HomeDataVo) cacheObject;
        return ResponseResult.success()
                .putExtra("articles",homeDataVo.getArticles())
                .putExtra("newArticleList",homeDataVo.getApiArticleListVOS())
                .putExtra("tagCloud",homeDataVo.getTags());

    }

    /**
     * 获取网站相关信息
     * @return
     */
    public ResponseResult getWebSiteInfo() {
        //网站信息
        WebConfig webConfig = webConfigMapper.selectOne(new LambdaQueryWrapper<WebConfig>()
                .select(WebConfig::getAuthorAvatar,WebConfig::getIsMusicPlayer,WebConfig::getAuthorInfo,WebConfig::getTouristAvatar,WebConfig::getBulletin,
                        WebConfig::getQqNumber,WebConfig::getGitee,WebConfig::getGithub,WebConfig::getLogo,WebConfig::getWechat,
                        WebConfig::getAboutMe,WebConfig::getEmail,WebConfig::getShowList,WebConfig::getLoginTypeList,
                        WebConfig::getRecordNum,WebConfig::getAuthor,WebConfig::getAliPay,WebConfig::getWeixinPay,
                        WebConfig::getQqGroup,WebConfig::getWebUrl, WebConfig::getSummary,WebConfig::getName,WebConfig::getKeyword)
                .last(LIMIT_ONE));

        //获取访问量
        Object count = redisService.getCacheObject(RedisConstants.BLOG_VIEWS_COUNT);
        //获取访客量
        Long visitorAccess = redisService.getCacheSetKeyNumber(RedisConstants.UNIQUE_VISITOR);
        //热门文章
        List<ApiArticleListVO> hotArticles = articleMapper.selectHotArticleList();
        return ResponseResult.success(webConfig)
                .putExtra("siteAccess", Optional.ofNullable(count).orElse(0))
                .putExtra("visitorAccess",visitorAccess)
                .putExtra("hotArticles",hotArticles);
    }

//    /**
//     * 获取各大平台的热搜
//     * @param type 平台
//     * @return
//     */
    @Override
    public ResponseResult hot(String type) {
        String url = "https://www.coderutil.com/api/resou/v1/" + type;
        JSONObject jsonObject = MyHttpUtil.sendCuApiHttpUrl(url);
        return ResponseResult.success(null);
    }
}
